package cn.cocho.common.web.jqgrid;

import cn.cocho.dborm.core.DataTypeConverter;
import cn.cocho.dborm.core.Dborm;
import cn.cocho.dborm.util.PairDborm;
import cn.cocho.common.web.character.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shk on 14-7-26.
 */
public class JQGridUtils {

    Logger logger = Logger.getLogger(JQGridUtils.class.getName());
    DataTypeConverter dataTypeConverter = new DataTypeConverter();

    @Autowired
    Dborm dborm;

    public <T> JQGridPage getListByJQgrid(JQGridPage pageJQGrid, Class<T> entityClass, String tableName) {
        pageJQGrid.initJqGrid();
        PairDborm<String, List<Object>> dataPair = getDataPair(pageJQGrid, tableName);
        List<T> userInfoList = dborm.getEntities(dataPair.first, dataPair.second.toArray(), entityClass);
        pageJQGrid.setDataRows(userInfoList);
        PairDborm<String, List<Object>> countPair = getCountPair(pageJQGrid, tableName);
        Integer count = dborm.getCount(countPair.first, countPair.second.toArray());
        if (count != null) {
            pageJQGrid.setRecords(count);
        }
        return pageJQGrid;
    }

    public PairDborm<String, List<Object>> getDataPair(JQGridPage page, String tableName) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT * FROM ");
        sql.append(tableName);
        sql.append(" WHERE 1=1 ");
        PairDborm<String, List<Object>> filterPair = getFilter(page);
        sql.append(filterPair.first);
        return PairDborm.create(sql.toString(), filterPair.second);
    }


    public PairDborm<String, List<Object>> getCountPair(JQGridPage page, String tableName) {
        StringBuilder sql = new StringBuilder();
        List<Object> ruleDatas = new ArrayList<Object>();
        sql.append(" SELECT COUNT(*) FROM ");
        sql.append(tableName);
        sql.append(" WHERE 1=1 ");
        PairDborm<String, List<Object>> rulesPair = getRules(page);
        sql.append(rulesPair.first);
        return PairDborm.create(sql.toString(), rulesPair.second);
    }

    public boolean delete(String sqlDelete, String ids) {
        PairDborm<String, List<Object>> deletesPair = deletesPair(ids);
        StringBuilder sql = new StringBuilder(sqlDelete);
        sql.append(" in (");
        sql.append(deletesPair.first);
        sql.append(")");
        return dborm.execSql(sql.toString(), deletesPair.second.toArray());
    }

    public PairDborm<String, List<Object>> deletesPair(String ids) {
        StringBuilder sql = new StringBuilder();
        List<Object> idDatas = new ArrayList<Object>();
        String[] idArray = ids.split(",");
        StringBuilder sqlWhere = new StringBuilder();
        for (String id : idArray) {
            sqlWhere.append("?,");
            idDatas.add(id);
        }
        sql.append(StringUtils.cutLastSign(sqlWhere.toString(), ","));
        return PairDborm.create(sql.toString(), idDatas);
    }


    public PairDborm<String, List<Object>> getRules(JQGridPage page) {
        StringBuilder sql = new StringBuilder();
        List<Object> ruleDataList = new ArrayList<Object>();
        if (page.getJqGridFilter() != null && page.getJqGridFilter().getRules() != null) {
            String op = page.getJqGridFilter().getGroupOp();
            List<JQGridRules> rules = page.getJqGridFilter().getRules();
            for (JQGridRules rule : rules) {
                sql.append(op);
                sql.append(" ");
                sql.append(rule.getField());
                sql.append(" ");
                if ("eq".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" =? ");
                    ruleDataList.add(dataTypeConverter.fieldValueToColumnValue(rule.getData()));
                } else if ("ne".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" !=? ");
                    ruleDataList.add(dataTypeConverter.fieldValueToColumnValue(rule.getData()));
                } else if ("in".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" >? ");
                    ruleDataList.add(dataTypeConverter.fieldValueToColumnValue(rule.getData()));
                } else if ("ni".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" <? ");
                    ruleDataList.add(dataTypeConverter.fieldValueToColumnValue(rule.getData()));
                } else if ("cn".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" LIKE ? ");
                    ruleDataList.add("%" + dataTypeConverter.fieldValueToColumnValue(rule.getData()) + "%");
                } else if ("nc".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" NOT LIKE ? ");
                    ruleDataList.add("%" + dataTypeConverter.fieldValueToColumnValue(rule.getData()) + "%");
                }else if ("bw".equalsIgnoreCase(rule.getOp())) {
                    sql.append(" LIKE ? ");
                    ruleDataList.add("" + dataTypeConverter.fieldValueToColumnValue(rule.getData()) + "%");
                }
            }
        }
        return PairDborm.create(sql.toString(), ruleDataList);
    }

    public PairDborm<String, List<Object>> getFilter(JQGridPage page) {
        PairDborm<String, List<Object>> rulesPair = getRules(page);
        StringBuilder sql = new StringBuilder(rulesPair.first);
        List<Object> dataList = rulesPair.second;
        if (StringUtils.isBlank(page.getSidx()) || StringUtils.isBlank(page.getSord())) {
            sql.append(" ORDER BY last_modify_time DESC ");
        } else {
            sql.append(" ORDER BY ");
            sql.append(page.getSidx());
            sql.append(" ");
            sql.append(page.getSord());
        }
        sql.append(" LIMIT ?");
        dataList.add(dataTypeConverter.fieldValueToColumnValue(page.getRows()));
        sql.append(" OFFSET ?");
        dataList.add(dataTypeConverter.fieldValueToColumnValue(page.getPageFirst()));
        return PairDborm.create(sql.toString(), dataList);
    }

    public void warnUserMessage(String warnMessage, HttpServletResponse response){
        if (warnMessage != null) {
            response.setContentType("text/json; charset=UTF-8");
            try {
                PrintWriter out = response.getWriter();
                out.print(warnMessage);
            } catch (Exception e) {
                logger.error(e);
            }
        }
    }


}
